/**
 * @作者 faner
 * @创建时间 2021/1/20 18:16
 */
package com.faner.fast.config.mybatis;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.faner.fast.constant.CommonConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Slf4j
@Component // 一定不要忘记把处理器加到IOC容器中！
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("start insert fill.....");
        //判断是否有createTime字段，有就自动填充，没有就跳过
        // setFieldValByName(String fieldName, Object fieldVal, MetaObject metaObject
        boolean bCreateTime = metaObject.hasSetter("createTime");
        if (bCreateTime){
            this.setFieldValByName("createTime", LocalDateTime.now(),metaObject);
        }
        boolean bUpdateTime = metaObject.hasSetter("updateTime");
        if (bUpdateTime){
            this.setFieldValByName("updateTime",LocalDateTime.now(),metaObject);
        }
        boolean bDelFlag = metaObject.hasSetter("delFlag");
        if (bDelFlag){
            this.setFieldValByName("delFlag", CommonConstants.STATUS_NORMAL,metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("start update fill.....");
        // 判断是否已经设置好了updateTime字段，有就自动填充，没有就跳过
        Object valueUpdateTime = getFieldValByName("updateTime", metaObject);
        if (null == valueUpdateTime){
            this.setFieldValByName("updateTime",LocalDateTime.now(),metaObject);
        }
    }
}
